package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/hyperledger/fabric/core/chaincode/shim"
	pb "github.com/hyperledger/fabric/protos/peer"
)

type DaoValueChaincode struct {
}

type DaoValue struct {
	UserId int64 `json:"userId"`
	UserName string `json:"userName"`
	Avatar string `json:"avatar"`
	DaoValue float64 `json:"daoValue"`
	UpdateTime string `json:"updateTime"`
}

func main() {
	err := shim.Start(new(DaoValueChaincode))
	if err != nil {
		fmt.Errorf(err.Error())
	}
}

func (d DaoValueChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {
	return shim.Success(nil)
}

func (d DaoValueChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {

	fc, args := stub.GetFunctionAndParameters()
	if fc == "add" {
		return d.Add(stub, args)
	}

	return shim.Error("function is nil")
}

func (d DaoValueChaincode) Add(stub shim.ChaincodeStubInterface, args []string) pb.Response {

	if len(args) != 1 {
		return shim.Error(parameterErr.Error())
	}

	var daos []DaoValue
	err := json.Unmarshal([]byte(args[0]), &daos)
	if err != nil {
		return shim.Error(err.Error())
	}

	err = batchSaveDaos(stub, daos)
	if err != nil {
		return shim.Error(err.Error())
	}

	return success
}

func batchSaveDaos(stub shim.ChaincodeStubInterface, daos []DaoValue) error {
	for _, dao := range daos {
		db, err := json.Marshal(dao)
		if err != nil {
			return err
		}
		err = stub.PutState(string(dao.UserId), db)
		if err != nil {
			return err
		}
	}
	return nil
}

func getDao(stub shim.ChaincodeStubInterface, id string) (*DaoValue, error) {
	db, err := stub.GetState(id)
	if err != nil {
		return nil, err
	}
	if db == nil {
		return nil, nil
	}
	var dao DaoValue
	err = json.Unmarshal(db, &dao)
	return &dao, nil
}

var parameterErr = errors.New("parameter err")

var success = shim.Success([]byte("success"))